<template>
  <div class="page-content">
    <!-- 判断 pageJsonData 是否有数据 -->
    <div style="width: 100%" v-if="pageJsonData && pageJsonData.length > 0">
      <draggable
        v-model="pageJsonData"
        :component-data="{
          tag: 'div',
          type: 'transition-group',
          name: !drag ? 'flip-list' : null,
        }"
        v-bind="buttonDragOptions"
        :disabled="!shouldShowDragHandle(pageJsonData)"
        @start="drag = true"
        @end="dragEnd"
        item-key="id"
      >
        <template #item="{ element: component, index }">
          <div
            class="item-button draggable-item component-wrapper"
            :class="{ 'sortable-disabled': !shouldShowDragHandle(pageJsonData) }"
            :key="component.id"
          >
            <component
              :is="getComponetnBytype(component.type)"
              :model-value="component"
              @update:model-value="($event) => updateComponentValue(index, $event)"
            />
            <div class="add-btn">
              <a-button type="primary" @click="addComponent(index)">
                <template #icon>
                  <icon-plus />
                </template>
                Add Component
              </a-button>
            </div>
          </div>
        </template>
      </draggable>
      <!-- <a-button type="primary" class="add-component-btn" @click="addComponent"> 添加组件 </a-button> -->

      <!-- <div v-for="(component, index) in pageJsonData" :key="component.id" class="page-item">
        <div class="component-wrapper">
          <component
            :is="getComponetnBytype(component.type)"
            :model-value="component"
            @update:model-value="($event) => updateComponentValue(index, $event)"
          />
          <div class="add-btn">
            <a-button type="primary" @click="addComponent(index)">
              <template #icon>
                <icon-plus />
              </template>
              Add Component
            </a-button>
          </div>
        </div>
      </div> -->
    </div>

    <div v-else>
      <!-- 使用 Arco Design 的按钮 -->
      <a-button type="primary" class="add-component-btn" @click="addComponent"> 添加组件 </a-button>
    </div>

    <component-selector v-model:visible="visible" @ok="addComponentToPage" />
  </div>
</template>

<script setup>
// import * as allPageComponents from "officialblock";
import { ref, watch, computed, defineAsyncComponent } from "vue";
import componentSelector from "./ComponentSelector/index.vue";
// 动态导入 draggable，避免 SSR 问题
const draggable = defineAsyncComponent(() => import("vuedraggable"));

// 拖拽相关状态
const drag = ref(false);

// 接收外部传入的数据
const props = defineProps({
  data: {
    type: Array,
    default: () => [],
  },
});

const emit = defineEmits(["update"]);

// 动态导入components目录下的所有组件
const modules = import.meta.glob("@/components/*/index.vue", { eager: false });

const componentMap = {};

// 遍历并注册组件
// 遍历并注册组件，使用文件夹名称作为组件名
for (const path in modules) {
  try {
    // 正确提取文件夹名称
    const pathParts = path.split("/");
    const folderName = pathParts[pathParts.length - 2]; // 文件夹名称
    console.log(`注册组件: ${folderName} from ${path}`); // 调试信息
    componentMap[folderName] = defineAsyncComponent(modules[path]);
  } catch (error) {
    console.error("组件注册失败:", path, error);
  }
}
const getComponetnBytype = (type) => {
  return componentMap[type];
};

// const componentMap = allPageComponents;
const visible = ref(false);
const selectComponentIndex = ref(0);

// 响应式数据
const pageJsonData = ref([...props.data]);

// 当外部 modelValue 变化时，同步更新本地数据
watch(
  () => props.data,
  (newVal) => {
    pageJsonData.value = [...newVal];
  },
  { deep: true }
);

const buttonDragOptions = computed(() => ({
  animation: 200,
  group: "buttons", // 按钮专用分组
  disabled: false,
  ghostClass: "ghost",
}));

// 检查是否应该显示拖拽图标
const shouldShowDragHandle = (list) => {
  return list && list.length > 1;
};

// 添加组件的方法
const addComponent = (index = 0) => {
  selectComponentIndex.value = index;
  visible.value = true;
};

const updateComponentValue = (index, value) => {
  pageJsonData.value[index] = value;
  emit("update", [...pageJsonData.value]);

  console.log("组件更新:", pageJsonData.value);
};
const dragEnd = () => {
  drag.value = false;
  emit("update", [...pageJsonData.value]);
};

// 弹框添加
const addComponentToPage = (json) => {
  visible.value = false; // 手动将新对象转为响应式对象
  pageJsonData.value.splice(selectComponentIndex.value + 1, 0, json);
  emit("update", [...pageJsonData.value]);
};
</script>

<style lang="scss" scoped>
.page-content {
  // height: 100%;
  min-height: 500px;
  // display: flex;
  // flex-direction: column;
  // align-items: center;
  // justify-content: center;
  padding: 30px 0 50px;

  // .page-item {
  //   min-width: none;
  //   height: 100%;

  .component-wrapper {
    position: relative;

    &:hover {
      border: 2px solid #409eff;

      .add-btn {
        display: block;
      }
    }

    .add-btn {
      display: none;
      position: absolute;
      left: 50%;
      bottom: 0;
      transform: translate(-50%, 50%);
    }
  }
  // }

  .add-component-btn {
    padding: 12px 24px;
    font-size: 16px;
  }
}
</style>
